package linkedlist.other;

import linkedlist.Node;
import linkedlist.create.RecursionLinkedCreator;

import java.util.Arrays;
import java.util.Stack;

/**
 * @Author wangtengyu
 * @Create 2018-09-05-15:13 从尾到头打印链表 1.改变链表的结构 链表反转后打印即可 2.不改变链表的结构（这里讲的是这种方式） 一个先进后出的思想
 */
public class PrintFromTail {


  /**
   * 通过栈来实现
   */
  public void pirntByStack(Node head) {
    Stack<Node> stack = new Stack();
    Node newHead = head;
    while (newHead != null) {
      stack.add(newHead);
      newHead = newHead.getNext();
    }
    while (!stack.isEmpty()) {
      System.out.print(stack.pop().getData() + " ");
    }

  }

  /**
   * 通过递归来实现
   */
  public void printByRecursion(Node head) {
    if (head == null) {
      return;
    }

    printByRecursion(head.getNext());
    System.out.println(head.getData());
  }


  public static void main(String[] args) {
    RecursionLinkedCreator creator = new RecursionLinkedCreator();
    PrintFromTail printFromTail = new PrintFromTail();
    Node node = creator.createlinkedList(Arrays.asList(1, 2, 3, 4, 5));
    printFromTail.pirntByStack(node);
//        printFromTail.printByRecursion(node);
  }


}
